#include "Console.h"
#include "Messages.h"

char* conGets(char* out,int size);

/* Internal */
/*void conFlush(){
	fpurge()
}*/

char* conGets(char* buf,int size){
	int len;
	
	fgets(buf,size,stdin);
	len = strlen(buf);

	if(len >= 1 && (buf[len-1] == '\n' || buf[len-1] == '\r')) buf[len-1] = '\0';
	if(len >= 2 && (buf[len-2] == '\n' || buf[len-2] == '\r')) buf[len-2] = '\0';
	
	return buf;
}

/* Methodes */
#define CON_PQON_BUFSIZE 6
int conPoserQuestionON(char* question){
	char* ansOui[]= { "O","o","oui","OUI" };
	char* ansNon[]= { "N","n","non","NON" };
	char* buf;
	int i;
	
	eassert(question != NULL);
	
	while(1){
		printf("%s (O\\N)\n",question);
		
		buf = emalloc(CON_PQON_BUFSIZE);
		if(buf == NULL) return 0;
		
		conGets(buf,CON_PQON_BUFSIZE);
		
		for(i = 0; i < (int)sizeof(ansOui); i++)
			if(strcmp(buf,ansOui[i]) == 0) return 1;
		
		for(i = 0; i < (int)sizeof(ansNon); i++)
			if(strcmp(buf,ansOui[i]) == 0) return 0;
	
		printf("%s\n",MES_PQON_ER);
	}
	
	return 0;
}

#define CON_CHOISIR_BUFSIZE 3
int conChoisir(char* message,List* l){
	char* prop;
	char* buf;
	int i,rep;
	eassert(message != NULL);
	eassert(l != NULL);
	
	while(1){
		printf("%s\n",message);
		
		i = 0;
		listForEach(prop,l)
			printf("[%d] %s",++i,prop);
		
		buf = emalloc(CON_CHOISIR_BUFSIZE);
		if(buf == NULL) return 0;
		
		conGets(buf,CON_CHOISIR_BUFSIZE);
		
		rep = atoi(buf);
		if(rep > 0 && rep <= listGetSize(l)) return rep-1;
	
		printf("%s\n",MES_CHOISIR_ER);
	}
	
	return 0;
}

#define CON_PQS_BUFSIZE 300
int conPoserQuestionStr(char* question,char** reponse){
	char* buf;
	eassert(question != NULL);
	
	printf("%s\n",question);
	
	buf = emalloc(CON_PQS_BUFSIZE);
	if(buf == NULL) return 0;
	
	while(strlen(buf) == 0)
		conGets(buf,CON_PQS_BUFSIZE);
	
	*reponse = buf;
	
	return 0;
}

